package mk.edu.ii.navigatemacedonia;



import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class NavigateMacedonia extends Activity {
	private static final String USER_PREFERENCE = "user_preference";
	ArrayList<Site> sites=new ArrayList<Site>();
	LocationManager myLocationManager;
	ProgressBar progressBar;
	View view;
	Spinner radiusSpiner;
    Spinner categorySpiner;
    Spinner subcategorySpiner;
    
    
			
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nm_mainview);
        radiusSpiner = (Spinner)findViewById(R.id.first_RadiusSpiner);
        categorySpiner = (Spinner)findViewById(R.id.first_CategorySpiner);
        subcategorySpiner = (Spinner)findViewById(R.id.first_SubcategorySpiner);
        CheckBox checkBox = (CheckBox)findViewById(R.id.check_box);
        checkBox.setChecked(false);
        progressBar = (ProgressBar)findViewById(R.id.ProgressBar);
        
        progressBar.setVisibility(View.INVISIBLE);
        populateSpinners(radiusSpiner,R.array.radius);
        populateSpinners(categorySpiner,R.array.category);
        
        
        final Button searchButton = (Button) findViewById(R.id.SearchButton);
        final Button pickLocationButton = (Button) findViewById(R.id.PickLocationButton);
        
        pickLocationButton.setOnClickListener(new Button.OnClickListener() {
    		public void onClick(View v){
    			saveUIState();
    			pickLocation();
    		}
        });
		
        searchButton.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v){
				
				searchButton();
			}
		});
		
		categorySpiner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        	public void onItemSelected( AdapterView<?> parent, View view, int position, long id){
        		switch ((int)id) {
        		case 0:{
        			populateSpinners(subcategorySpiner, R.array.all);
        			return;
        		}
               	case 1:{
               		populateSpinners(subcategorySpiner, R.array.historical_subcategory);
               		return;
               	}
               	case 2:{
               		populateSpinners(subcategorySpiner, R.array.stores_subcategory);
               		return;
               	}
               	case 3:{
               		populateSpinners(subcategorySpiner, R.array.food_subcategory);
               		return;
               	}
               	case 4:{
               		populateSpinners(subcategorySpiner, R.array.bars_subcategory);
               		return;
               	}
        		}    			
        	}
        	public void onNothingSelected(AdapterView<?> parent){
        		populateSpinners(subcategorySpiner, R.array.all);
        	}
        });
		//restoreUIState();
	}
    
    public Location getMyLocation(){
    	testProviders();
		//get reference to Location Manager and Location Provider
        myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        
        try{
    		Criteria criteria = new Criteria();
    		criteria.setAccuracy(Criteria.ACCURACY_FINE);
    		criteria.setAltitudeRequired(false);
    		criteria.setBearingRequired(true);
    		criteria.setCostAllowed(true);
    		criteria.setPowerRequirement(Criteria.POWER_LOW);
    		LocationManager locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);
    		String provider = locationManager.getBestProvider(criteria, true);
    		Location location = myLocationManager.getLastKnownLocation(provider);
    		
    		return location;
    	}
        catch (Exception e) {
        	Toast toast = Toast.makeText(getApplicationContext()
        		, "Your location can not be determined!"
        		, Toast.LENGTH_SHORT);
        	toast.show();
        	progressBar.setVisibility(ProgressBar.INVISIBLE);
        	}
        return null;
    }
    
    public void populateSpinners(Spinner spinner,int id){
    	
    	ArrayAdapter<CharSequence> aAdapter;
    	
    	aAdapter = ArrayAdapter.createFromResource(this,id,android.R.layout.simple_spinner_item);
    	aAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	spinner.removeAllViewsInLayout();
    	spinner.setAdapter(aAdapter);
    	//spinner.setSelection(1);
    }
    
    public void testProviders() {
    	
    	myLocationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
    	LocationProvider provider = myLocationManager.getProvider(LocationManager.GPS_PROVIDER);
    	LocationListener listener = new LocationListener() {
        	public void onLocationChanged(Location location) {}
        	public void onProviderDisabled(String provider){}
        	public void onProviderEnabled(String provider){}
        	public void onStatusChanged(String provider, int status,
        	Bundle extras){}
        	};
    	myLocationManager.requestLocationUpdates(provider.getName(), 1000, 0, listener);
    	myLocationManager.removeUpdates(listener);
    	
    }
    
    protected void onResume() {
    	progressBar.setVisibility(ProgressBar.INVISIBLE);
    	restoreUIState();
    	super.onResume();    	  	
    }
    
    @Override
    protected void onPause(){
    	saveUIState();
    	super.onPause();
    	
    }
    
    public void pickLocation(){
    	
    	Intent pickLocationIntent = new Intent(getApplicationContext(),PickLocationMapView.class);
    	startActivity(pickLocationIntent);
    }
    
    public void searchButton(){
    	progressBar.setVisibility(View.VISIBLE);
		CheckBox checkBox = (CheckBox)findViewById(R.id.check_box);
		Location location = new Location(LocationManager.GPS_PROVIDER);
		
		int[] rad= {100,250,500,1000,1500,2000,5000};
		ServiceConnect serviceConnect= new ServiceConnect();
		Intent intent = getIntent();
		if(checkBox.isChecked() && intent!=null){
			location.setLatitude(intent.getDoubleExtra("latitude", 0d));
			location.setLongitude(intent.getDoubleExtra("longitude", 0d));	
		}else{
			location=getMyLocation();
		}
		if(location!=null){
			
        sites = serviceConnect.getSitesFromService(getApplicationContext()
        		,location.getLongitude()
        		,location.getLatitude()
        		,rad[radiusSpiner.getSelectedItemPosition()]
        		,(String)categorySpiner.getSelectedItem());
        
        if (sites!=null){
       
		Intent resultsView = new Intent(getApplicationContext(),ResultsView.class);
		resultsView.putExtra("sites", sites);
		resultsView.putExtra("longitude", location.getLongitude());
		resultsView.putExtra("latitude", location.getLatitude());
    	startActivity(resultsView);
    	progressBar.setVisibility(View.INVISIBLE);
        }
        else{
        	
        	String msg = "No sites found";
    		int duration = Toast.LENGTH_SHORT;
    		Toast toast = Toast.makeText(getApplicationContext(), msg, duration);
    		toast.show();
    		progressBar.setVisibility(ProgressBar.INVISIBLE);
        }			
	}
    }
    private void saveUIState(){
    	//     	Get the activity preferences object.
    	SharedPreferences uiState = getSharedPreferences(USER_PREFERENCE, Activity.MODE_PRIVATE);
    	 
    	// Get the preferences editor.
    	SharedPreferences.Editor editor = uiState.edit();
    	// Add the UI state preference values.
    	CheckBox checkBox = (CheckBox)findViewById(R.id.check_box);
    	radiusSpiner = (Spinner)findViewById(R.id.first_RadiusSpiner);
        categorySpiner = (Spinner)findViewById(R.id.first_CategorySpiner);
        subcategorySpiner = (Spinner)findViewById(R.id.first_SubcategorySpiner);
        
    	editor.putBoolean("CHECK_BOX", checkBox.isChecked());
    	editor.putLong("radius", radiusSpiner.getSelectedItemPosition());
    	editor.putLong("category", categorySpiner.getSelectedItemPosition());
    	editor.putLong("subcategory", subcategorySpiner.getSelectedItemPosition());
    	// Commit the preferences.
    	editor.commit();
    }
    private void restoreUIState() {
    	// Get the activity preferences object.
    	SharedPreferences settings = getSharedPreferences(USER_PREFERENCE, Activity.MODE_PRIVATE);
    	// Read the UI state values, specifying default values.
    	
    	Boolean check_box = settings.getBoolean("CHECK_BOX", false);
    	// Restore the UI to the previous state.
    	CheckBox checkBox = (CheckBox)findViewById(R.id.check_box);
    	radiusSpiner = (Spinner)findViewById(R.id.first_RadiusSpiner);
        categorySpiner = (Spinner)findViewById(R.id.first_CategorySpiner);
        subcategorySpiner = (Spinner)findViewById(R.id.first_SubcategorySpiner);
        
    	checkBox.setChecked(check_box);
    	radiusSpiner.setSelection((int)settings.getLong("radius", 0));
    	categorySpiner.setSelection((int)settings.getLong("category", 0));
    	subcategorySpiner.setSelection((int)settings.getLong("subcategory", 0));
    	}
}